﻿#include "qsimulation.h"
#include "ui_qsimulation.h"
#include <QMessageBox>

QSimulation::QSimulation(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::QSimulation)
{
    ui->setupUi(this);
    //初始化TCP客户端
    tcpClient = new QTcpSocket(this);   //实例化tcpClient
    tcpClient->abort();                 //取消原有连接

    connect(tcpClient, SIGNAL(readyRead()), this, SLOT(ReadData()));
    connect(tcpClient, SIGNAL(error(QAbstractSocket::SocketError)), \
            this, SLOT(ReadError(QAbstractSocket::SocketError)));
}

QSimulation::~QSimulation()
{
    delete ui;  //
}

void QSimulation::ReadData()
{
    QByteArray buffer = tcpClient->readAll();
    if(!buffer.isEmpty())
    {
 //       ui->edtRecv->append(buffer);
        ui->textEdit_2->append(buffer.toHex()); //16进制显示出来数据
    }
}

void QSimulation::ReadError(QAbstractSocket::SocketError)
{
    tcpClient->disconnectFromHost();
    QMessageBox msgBox;
    msgBox.setText(tr("failed to connect server because %1").arg(tcpClient->errorString()));
    msgBox.exec();
    ui->btn_break->setEnabled(false);
    ui->btn_link->setEnabled(true);
}

void QSimulation::on_btn_link_clicked()
{
    QString addr = ui->comboBox->currentText();
    quint32 port = ui->comboBox_2->currentText().toUInt();
    tcpClient->connectToHost(addr,(quint16)port); //连接
    ui->btn_link->setEnabled(false);
    ui->btn_break->setEnabled(true);
}

void QSimulation::on_btn_break_clicked()
{
    if(tcpClient->state() == QAbstractSocket::ConnectedState)
    {
        tcpClient->disconnectFromHost();
        ui->btn_break->setEnabled(false);
        ui->btn_link->setEnabled(true);
    }
}

void QSimulation::on_btn_online_clear_clicked()
{

}

void QSimulation::on_btn_work_clear_clicked()
{

}

void QSimulation::on_brn_ele_clear_clicked()
{

}

void QSimulation::on_btn_send_work_clicked()
{

}

void QSimulation::on_btn_clear_accept_clicked()
{
    ui->textEdit_2->clear();
}
